package com.example.taobao

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.fragment_xiaoxi.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.net.URLEncoder
import kotlin.concurrent.thread



private var msglist:ArrayList<msginfo> = ArrayList<msginfo>()
class Fragment_xiaoxi : Fragment() {
    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            msglist = msg.obj as ArrayList<msginfo>
            val layoutManager = LinearLayoutManager(context)
            xiaoxiview.layoutManager = layoutManager
            val adapter = msgAdapter(msglist)
            xiaoxiview.adapter = adapter
            adapter.notifyDataSetChanged()
        }
    }

    fun refresh()
    {
        val layoutManager = LinearLayoutManager(context)
        xiaoxiview.layoutManager = layoutManager
        val adapter = msgAdapter(msglist)
        xiaoxiview.adapter = adapter
        adapter.notifyDataSetChanged()
    }

    public fun tiaoz1(meg:String)
    {
        // var bundle = Bundle()
        // bundle.putStringArrayList("message",meg)
        var intent: Intent = Intent()
        intent?.putExtra("message",meg)
        intent = Intent(activity, Messagedetail::class.java)
        startActivity(intent)
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_xiaoxi,container,false)
        return view
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        jiy.setOnClickListener {
            val intent = Intent(activity, Myorder::class.java)
            startActivity(intent)
        }
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
        refresh()
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            initData()
            refresh()
        }
    }

    override fun onResume() {
        super.onResume()
        initData()
        refresh()
    }

    private inner class msgViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvname1: TextView = view.findViewById(R.id.name)
        val tvmsg: TextView = view.findViewById(R.id.msg)
        val tvtime: TextView = view.findViewById(R.id.time)
        val tvmegpic: CircleImageView = view.findViewById(R.id.touxiang1)
        val tvdelete :ImageButton = view.findViewById(R.id.delete)
    }

    private inner class msgAdapter(val msgList: List<msginfo>) :
        RecyclerView.Adapter<msgViewHolder>() {
        private var itemClickListener: IKotlinItemClickListener? = null
        override fun getItemCount() = msgList.size
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): msgViewHolder {
            val view =
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.messagedetail, parent, false)
            return msgViewHolder(view)
        }

        override fun onBindViewHolder(holder: msgViewHolder, position: Int) {
            val info = msgList[position]
            holder.tvname1.text = info.name
            Glide.with(this@Fragment_xiaoxi)
                .load(info.megpic)
                .into(holder.tvmegpic)
            holder.tvmsg.text = info.mas
            holder.tvdelete.setOnClickListener {
                val prefs =activity?.getSharedPreferences("data", Context.MODE_PRIVATE)
                val username = prefs?.getString("name","未登录")
                thread {
                    try {
                        var meg :ArrayList<MsgContentBean> = ArrayList<MsgContentBean>()
                        val client = OkHttpClient()
                        val requestBody = FormBody.Builder()
                            .add("name", URLEncoder.encode(info.name, "utf-8"))
                            .add("username", URLEncoder.encode(username, "utf-8"))
                            .build()
                        val request = Request.Builder()
                            .url("http://192.168.43.140:8080/aaa_war_exploded/deletemeg.jsp")
                            .post(requestBody)
                            .build()
                        val respone = client.newCall(request).execute()
                        val responeData = respone.body!!.string()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                msglist.removeAt(position)
                refresh()
            }
            holder.tvtime.text = info.time
            val meg : ArrayList<String> = ArrayList<String>()
            holder.tvname1.setOnClickListener {
                meg.clear()
                meg.add(info.name)
                tiaoz1(info.name)
                val editor = activity?.getSharedPreferences("data",Context.MODE_PRIVATE)?.edit()
                editor?.putString("megname",info.name)
                editor?.putString("megpic",info.megpic)
                editor?.apply()
            }
            // 提供set方法
            holder.itemView.setOnClickListener {
                tiaoz1(info.name)
                val editor = activity?.getSharedPreferences("data",Context.MODE_PRIVATE)?.edit()
                editor?.putString("megname",info.name)
                editor?.apply()
            }
            fun setOnKotlinItemClickListener(itemClickListener: IKotlinItemClickListener) {
                this.itemClickListener = itemClickListener
            }
        }
    }


    private fun initData() {
        thread {
            try {
                var meg: ArrayList<msginfo> = ArrayList<msginfo>()
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.43.140:8080/aaa_war_exploded/getallmeg.jsp")
                    .build()
                val respone = client.newCall(request).execute()
                val responeData = respone.body!!.string()
                meg = parseJosn(responeData)
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)

            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }

    fun parseJosn(jsonStr: String): ArrayList<msginfo> {
        val messaged: ArrayList<msginfo> = ArrayList<msginfo>()
        val Msbean: ArrayList<MsgContentBean> = ArrayList<MsgContentBean>()
        try {
            val gson = Gson()
            val jaonArray = JSONArray(jsonStr)
            for (i in 0 until jaonArray.length()) {
                val jsonObject = jaonArray.getJSONObject(i)
                val name = jsonObject.getString("name")
                val mas = jsonObject.getString("mas")
                val time = jsonObject.getString("time")
                val username = jsonObject.getString("username")
                val megpic:String = jsonObject.getString("megpic")
                messaged.add(
                    com.example.taobao.msginfo(
                        "${name}",
                        "${mas}",
                        "${time}",
                        Msbean,
                        "${username}","${megpic}"
                    )
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return messaged
    }

}